﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Jumpton.SFA.Server.BusinessRule.MasterData;
using Jumpton.SFA.Server.Entity;
using Jumpton.Persistent;
using Jumpton.SFA.Server.BusinessRule;
using Jumpton.SFA.Server.BusinessRule.System;
public partial class Order_Maintain : PageBase
{
    private decimal customerID = 0;
    private string orderID ="";
    private const string CUSTOMER_ID = "customerID";
    private const string ORDER_ID = "orderID";
    private const string RETURN_PAGE = "OrderQuery.aspx";


    protected void Page_Load(object sender, EventArgs e)
    {

        if (Request.QueryString[CUSTOMER_ID] != null)
        {
            decimal.TryParse(Request.QueryString[CUSTOMER_ID], out customerID);
        }
        if (Request.QueryString[ORDER_ID] != null)
        {
            orderID=Request.QueryString[ORDER_ID];
        }
        
        if (!IsPostBack)
        {
            InitForm();
            FillForm();

        }
        
    }


    /// <summary>
    /// Inits the form.
    /// </summary>
    private void InitForm()
    {
        txtStartDate.Text = DateTime.Now.ToShortDateString();
        txtDeliveryDate.Text = DateTime.Now.AddDays(3).ToShortDateString();
        if (customerID > 0)
        {
            CUSTOMERS customer = new CustomerManager().Load(customerID);
            if(customer!=null)
                lblCustomer.Text = customer.NAME;

        }
        
    }

    protected void SelectALL(object sender, EventArgs e)
    {
        CheckBox chk = sender as CheckBox;
        if (chk == null)
            return;
        foreach (GridViewRow row in gvOrderLineList.Rows)
        {
            CheckBox checkbox = row.Cells[gvOrderLineList.Columns.Count - 1].FindControl("chkConfirm") as CheckBox;
            if (checkbox != null)
                checkbox.Checked = chk.Checked;
        }
    }

    /// <summary>
    /// Fills the form.
    /// </summary>
    private void FillForm()
    {
        OrderHeaderManager headerManage = new OrderHeaderManager();
        OrderLineManager lineManager = new OrderLineManager();
        ChainManager chainManager = new ChainManager();

        if (!String.IsNullOrEmpty(orderID))
        {

            ORDER_HEADERS head = headerManage.Load(decimal.Parse(orderID));
            if (head != null)
            {
                txtOriginal.Text = (head.TOTAL_AMOUNT + head.DISC_AMOUNT).ToString();
                //下单时间
                txtStartDate.Text = BusinessLogic.GetDateTime(head.ORDER_date.ToString(),"yyyyMMddHHmmss","yyyy-MM-dd");
                this.txtOriginal.Text = head.TOTAL_AMOUNT.ToString();
                this.txtDiscount.Text = head.DISC_AMOUNT.ToString();
                this.txtFact.Text = (head.TOTAL_AMOUNT - head.DISC_AMOUNT).ToString();
                //请求发货时间
                txtDeliveryDate.Text = BusinessLogic.GetDateTime(head.REQ_DELIVERY_date.ToString(), "yyyyMMddHHmmss", "yyyy-MM-dd");
                //确认人
                try
                {
                    if (String.IsNullOrEmpty(head.CONFIRM_USER_CODE))
                        txtConfirmUser.Text = new PersonManager().Load(new UserManager().GetUserByCode(head.CONFIRM_USER_CODE).PERSONID).Name;
                    txtArrivalDate.Text = BusinessLogic.GetDateTime(head.ARRIVAL_DATE.ToString(), "yyyyMMddHHmmss", "yyyy-MM-dd");
                }
                catch { }
               
                try
                {
                    txtConfirmDate.Text = BusinessLogic.GetDateTime(head.ARRIVAL_DATE.ToString(), "yyyyMMddHHmmss", "yyyy-MM-dd HH:mm:ss");
                    if (txtConfirmDate.Text.Trim() == "")
                        txtConfirmDate.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                }
                catch
                {
                }
            
                //经销商
                try
                {
                    txtChains.Text = chainManager.Load(head.CHAIN_ID).DESCRIPTION;
                }
                catch { }

                chkCancelled.Checked = head.CANCELLED == null ? true : head.CANCELLED.Contains("N")?true:false;

            }
            DataSet ds = OrderLineManager.GetLineByOrderID(orderID);
            if (ds != null && ds.Tables.Count > 0)
            {
                ViewState["DataSource"] = ds.Tables[0];
               
            }
            gvOrderLineList.DataSource = ds.Tables[0];
            gvOrderLineList.DataBind();

           

        }
    }


    /// <summary>
    /// Handles the Click event of the btnSave control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            //会计期 是否能进行确认
            DateTime dt = new DateTime();
            if (DateTime.TryParse(txtArrivalDate.Text, out dt))
            {
                if (!FinancialMonthManager.IsOKtoConfirmByFinacialMonth(dt, MyStateManager.DomainID))
                {
                    throw new Exception("订单无法确认 理由:会计期关闭");
                }
            }

            #region 判断是否有跨行的订单
            foreach (GridViewRow row in gvOrderLineList.Rows)
            {
                CheckBox chk = (CheckBox)row.FindControl("chkConfirm");
                Label lblStatus = (Label)row.FindControl("lblStatusDescription");
                if (chk.Checked && lblStatus.Text == "已确认")
                {
                    DateTime arriveData = DateTime.Parse(txtArrivalDate.Text);
                    DateTime lineArriveData = DateTime.Parse(gvOrderLineList.DataKeys[row.RowIndex].Values["ARRIVAL_date"].ToString());
                    if (arriveData.Month > lineArriveData.Month)
                    {
                        ShowMessage("订单无法确认 理由:该订单行已经在上月确认过，不允许跨月确认");
                        return;
                    }
                }
            }
            #endregion

            this.SaveData(true);
            // this.ShowMessage("保存成功");
            // this.FillForm();
            Session["order_listisactive"] = "1";

            InitForm();
            this.FillForm();
            //Response.Redirect(RETURN_PAGE);
        }
        catch (Exception ex)
        {
            ShowMessage(ex.Message);
        }
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        Response.Redirect(RETURN_PAGE);

    }

    private void SaveData(bool Confirm)
    {
        OrderHeaderManager headerManager = new OrderHeaderManager();
        ORDER_HEADERS head;

        //没有订单则返回
        if (orderID == "")
            return;

        head = headerManager.Load(orderID);
        head.CONFIRMED_DATE= BusinessLogic.GetDateTimeDecimal(DateTime.Now);
        head.ARRIVAL_DATE = BusinessLogic.GetDateTimeDecimal(DateTime.Parse(this.txtArrivalDate.Text + " 12:00:00"));
        head.CONFIRM_USER_CODE = MyStateManager.Name;
        //发货时期
        head.REQ_DELIVERY_date =BusinessLogic.GetDateTimeDecimal(Convert.ToDateTime(this.txtArrivalDate.Text));
        //保存订单头
        headerManager.Save(head);
        string intOrderID = head.VISIT_ID.ToString();
        //确认数量
        int count = 0;

        bool isFinish = true;

        decimal totalQTY = 0;//单据总数
        decimal totalAmount = 0;//单据总价

        if (intOrderID!=null&&intOrderID != "")
        {
            ORDER_LINES line;
            OrderLineManager lineManager = new OrderLineManager();
            for (int i = 0; i <= this.gvOrderLineList.Rows.Count - 1; i++)
            {
                int _ProductID = 0;
                decimal amount = 0;//数量
                decimal qtyShip = 0;//发货数量
                decimal qtyReceive = 0;//收货数量
                decimal lineAmount = 0;//收货单价

                Label lblID = gvOrderLineList.Rows[i].FindControl("lblID") as Label;//Product_id
                Label lblLineID = gvOrderLineList.Rows[i].FindControl("lblLineID") as Label;//ORDER_LINES -- ID
                Label lblARRIVAL_date = gvOrderLineList.Rows[i].FindControl("lblARRIVAL_date") as Label; //收货时间
                CheckBox chkConfirm = gvOrderLineList.Rows[i].FindControl("chkConfirm") as CheckBox;
                //只有勾选收获的数据才会保存
                if (chkConfirm.Checked)
                {
                    //orderid 和 id
                    if (!string.IsNullOrEmpty(lblID.Text) && !string.IsNullOrEmpty(lblLineID.Text))
                    {
                        count++;

                        decimal lineID = decimal.Parse(lblLineID.Text);
                        line = lineManager.Load(decimal.Parse(lblLineID.Text));

                        decimal.TryParse((gvOrderLineList.Rows[i].FindControl("txtQTYShip") as TextBox).Text, out qtyShip);
                        line.QUANTITYSHIPPED = qtyShip*10;


                        decimal.TryParse((gvOrderLineList.Rows[i].FindControl("txtQTYReceive") as TextBox).Text, out qtyReceive);
                        line.QuantityReceived = qtyReceive*10;


                        decimal.TryParse((gvOrderLineList.Rows[i].FindControl("txtLinePrice") as TextBox).Text, out lineAmount);
                        line.LINEAMOUNT = lineAmount;
                        line.Confirm_user_code = MyStateManager.Name;
                        line.ARRIVAL_date = head.ARRIVAL_DATE;
                        line.Confirmed_Date = head.CONFIRMED_DATE;
                        if(Confirm)
                            line.OrderLineStatus = decimal.Parse(((int)EOrderLineStatus.已确认).ToString());

                        lineManager.Save(line);
                    }
                }
                if (!chkConfirm.Checked && string.IsNullOrEmpty(lblARRIVAL_date.Text))
                    isFinish = false;

                totalQTY += qtyReceive;
                totalAmount += (qtyReceive/10) * lineAmount;
            }
            //head = headerManager.Load(orderID);
            if (isFinish)
            {
                if (Confirm)
                    head.STATUS = decimal.Parse(((int)EOderStatus.已确认).ToString());
                head.TOTAL_AMOUNT = totalAmount;
                head.TOTAL_QUANTITY = totalQTY;
                headerManager.Save(head);
                ShowMessage("操作成功");
                return;
            }
            if ((count != gvOrderLineList.Rows.Count) && count > 0)
            {
                if (Confirm)
                    head.STATUS = decimal.Parse(((int)EOderStatus.部分确认).ToString());
                headerManager.Save(head);
                return;
            }
        }
    }

    private void UpdateViewState()
    {
        if (ViewState["DataSource"] != null)
        {
            DataTable dt = ViewState["DataSource"] as DataTable;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DropDownList ddl = gvOrderLineList.Rows[i].FindControl("ddlUOM") as DropDownList;
                dt.Rows[i]["UOM"] = ddl == null ? "" : ddl.SelectedValue;

                TextBox txt = gvOrderLineList.Rows[i].FindControl("txtQTYShip") as TextBox;
                dt.Rows[i]["QTYShip"] = txt == null ? "" : txt.Text;

                txt = gvOrderLineList.Rows[i].FindControl("txtQTYReceive") as TextBox;
                dt.Rows[i]["QTYReceive"] = txt == null ? "" : txt.Text;



            }
        }
    }


    protected void gvOrderLineList_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {

            TextBox txtQTYShip = (TextBox)e.Row.FindControl("txtQTYShip");//发货数量
            TextBox txtQTYReceive = (TextBox)e.Row.FindControl("txtQTYReceive");//收货数量
          
            TextBox txtLinePrice = (TextBox)e.Row.FindControl("txtLinePrice");//价格
            TextBox txtAmount = (TextBox)e.Row.FindControl("txtAmount");//数量
            Label lbl_price=(Label)e.Row.FindControl("lbl_price");//总金额
            Label lbl_kind = (Label)e.Row.FindControl("lbl_kind");//正常品，赠品
            CheckBox chkConfirm = (CheckBox)e.Row.FindControl("chkConfirm");
            LinkButton lbtn_Cancel = (LinkButton)e.Row.FindControl("lbtn_Cancel");
            txtQTYShip.Attributes.Add("onchange","updatePrice('"+txtQTYShip.ClientID+"','"+txtLinePrice.ClientID+"','"+lbl_price.ClientID+"')");
            txtLinePrice.Attributes.Add("onchange", "updatePrice('" + txtQTYShip.ClientID + "','" + txtLinePrice.ClientID + "','" + lbl_price.ClientID + "')");
            var row = e.Row.DataItem as DataRowView;
            string orderLineStatus = row["OrderLineStatus"].ToString();
            if (lbtn_Cancel != null)
                lbtn_Cancel.Attributes.Add("onclick", "return confirm('取消后不能恢复,确认要取消吗?');");
            //收货数量和发货数量默认为订单数量
            txtQTYShip.Text = string.IsNullOrEmpty(txtQTYShip.Text) ? txtAmount.Text : txtQTYShip.Text;
            txtQTYReceive.Text = string.IsNullOrEmpty(txtQTYReceive.Text) ? txtAmount.Text : txtQTYReceive.Text;
           
           
         
            this.Grid_RowDataBound(sender, e);
           



        }
    }


    protected void gvOrderLineList_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
       //没有订单则返回
        if (orderID == "")
            return;
        Label lblLineID = gvOrderLineList.Rows[e.RowIndex].FindControl("lblLineID") as Label;
        Label lblID = gvOrderLineList.Rows[e.RowIndex].FindControl("lblID") as Label;

        if (lblID != null && lblLineID != null)
        {
            ORDER_LINES obj = (ORDER_LINES)ObjectRow.Load(typeof(ORDER_LINES), "ID=" + lblLineID.Text);
            try
            {
                if (obj.OrderLineStatus == decimal.Parse(((int)EOrderLineStatus.已确认).ToString()))
                {
                    this.ShowMessage("操作失败：该订单已确认");
                    return;
                }
            }
            catch { }
            //TextBox box = gvChannelType.Rows[e.RowIndex].FindControl("txtCancelRemark") as TextBox;
            ////判断取消原应有否输入
            //if (string.IsNullOrEmpty(box.Text))
            //{
            //    this.ShowMessage("请输入取消原因");
            //    return;
            //}

            OrderLineManager.DeleteOneLineByLineID(decimal.Parse(lblLineID.Text));
            try
            {
                ORDER_LINES orderline = (ORDER_LINES)ORDER_LINES.Load(typeof(ORDER_LINES), "ID=" + lblLineID.Text);
                orderline.LAST_UPDATE_TIME = decimal.Parse(BusinessLogic.GetDateTimeString(DateTime.Now));
                orderline.LAST_UPDATER = MyStateManager.Name;
                //orderline.CANCELLED = //box.Text;//取消原因
                orderline.Save();
            }
            catch { }

          
        }
        this.FillForm();
        #region 订单行取消后 判断订单是否已经全部确认！
        OrderHeaderManager headerManager = new OrderHeaderManager();
        ORDER_HEADERS head;
        if (orderID != "")
        {
            head = headerManager.Load(orderID);
            //保存订单头
            headerManager.Save(head);
            decimal intOrderID = head.VISIT_ID;
            //是否更改为已确认
            bool isFinish = true;
            if (intOrderID != 0)
            {
                for (int i = 0; i <= this.gvOrderLineList.Rows.Count - 1; i++)
                {
                    Label lblARRIVAL_date = gvOrderLineList.Rows[i].FindControl("lblARRIVAL_date") as Label;
                    if (lblARRIVAL_date.Text == "")
                    {
                        isFinish = false;
                    }
                }
                if (this.gvOrderLineList.Rows.Count == 0)
                {
                    isFinish = false;
                }
                if (isFinish)
                {
                    head.STATUS = decimal.Parse(((int)EOderStatus.已确认).ToString());
                    head.LAST_UPDATE_TIME = decimal.Parse(BusinessLogic.GetDateTimeString(DateTime.Now));
                    head.LAST_UPDATER = MyStateManager.Name;
                    headerManager.Save(head);
                }
            }
        }
        #endregion
        //Response.Redirect(Request.RawUrl);
    }

   

    private void SetSelectedItem(ListControl list, String value)
    {
        foreach (ListItem e in list.Items)
            if (e.Value == value)
            {
                e.Selected = true;
                return;
            }
            else
                e.Selected = false;
    }


    protected void btnSave0_Click(object sender, EventArgs e)
    {
        try
        {
            //会计期 是否能进行确认
            DateTime dt = new DateTime();
            if (DateTime.TryParse(txtArrivalDate.Text, out dt))
            {
                if (!FinancialMonthManager.IsOKtoConfirmByFinacialMonth(dt, MyStateManager.DomainID))
                {
                    throw new Exception("订单无法确认 理由:会计期关闭");
                }
            }

            #region 判断是否有跨行的订单
            foreach (GridViewRow row in gvOrderLineList.Rows)
            {
                CheckBox chk = (CheckBox)row.FindControl("chkConfirm");
                Label lblStatus = (Label)row.FindControl("lblStatusDescription");
                if (chk.Checked && lblStatus.Text == "已确认")
                {
                    DateTime arriveData = DateTime.Parse(txtArrivalDate.Text);
                    DateTime lineArriveData = DateTime.Parse(gvOrderLineList.DataKeys[row.RowIndex].Values["ARRIVAL_date"].ToString());
                    if (arriveData.Month > lineArriveData.Month)
                    {
                        ShowMessage("订单无法确认 理由:该订单行已经在上月确认过，不允许跨月确认");
                        return;
                    }
                }
            }
            #endregion

            this.SaveData(false);
            InitForm();
            this.FillForm();
            //Response.Redirect(RETURN_PAGE);
        }
        catch (Exception ex)
        {
            ShowMessage(ex.Message);
        }
    }
}
